import { parseTime } from '@/utils'
import qs from 'qs'
import request from '@/utils/request'

export default {
  data() {
    return {
      // beginDate: parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
      // endDate: parseTime(new Date().getTime(), '{y}-{m}-{d} {h}:{i}:{s}'),
      pageSize: 5,
      pageIndex: 1,
      tableKey: 0,
      overAll: [], // 品牌的总览数据
      list: [], // 下边的列表数据
      total: 0,
      listLoading: true,
      listQuery: {
        // page: 1,
        // limit: 20
      },
      downloadLoading: false

    }
  },
  async created() {
  },
  methods: {
    async fetchData() {
      if (this.overAllUrl && this.overAllUrl.length > 0) {
        await this.fetchOverAll()
      }

      if (this.listUrl && this.listUrl.length > 0) {
        await this.fetchList()
      }
    },
    async fetchOverAll() {
      this.listLoading = true
      const res = await request({
        url: this.overAllUrl + '?' + qs.stringify(this.listQuery, { format: 'RFC3986' }),
        method: 'get',
        params: {}
      })
      this.overAll = [res.data]
      console.log('overAll的数据--->', JSON.stringify(this.overAll))
      this.listLoading = false
    },
    async fetchList() {
      this.listLoading = true
      const res = await request({
        url: this.listUrl + '?' + qs.stringify(this.listQuery, { format: 'RFC3986' }),
        method: 'get',
        params: {}
      })
      this.list = Array.isArray(res.data) ? res.data : res.data.list // 服务端返回数据格式差异兼容
      this.total = Array.isArray(res.data) ? 0 : res.data.total
      console.log('list的数据--->', JSON.stringify(this.list))
      this.listLoading = false
    },

    // @listener点击查询按钮
    async handleFilter(date) {
      this.listQuery.beginDate = date.beginDate
      this.listQuery.endDate = date.endDate
      console.log('date', date)
      this.listQuery.page = 1
      await this.fetchData()
    },
    download() {

    },
    handleDownload() {
      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 处理分页逻辑
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.pageIndex = val
    }
  }
}
